package com.step.scene.camera;

import javax.microedition.khronos.opengles.GL10;

import com.step.Step;
import com.step.math.Vector;

/**
 *  2Ｄ相机，主要用在2Ｄ显示上。默认相机的位置为屏幕中心点。
 * @author heop
 *
 */
public class GUICamera extends Camera{
	public static float MAX_ZOOM = 1000f;
	public static float MIN_ZOOM = 0.1f;
	
	public final Vector position;
	float zoom;
	final float frustumWidth;
	final float frustumHeight;
	
	public GUICamera(){
		this(Step.renderer.getWidth(), Step.renderer.getHeight());
	}
	
	public GUICamera(float frustumWidth, float frustumHeight) {
		super(CameraType.GUI_CAMERA);
		this.frustumWidth = frustumWidth;
		this.frustumHeight = frustumHeight;
		this.zoom = 1;
		this.position = new Vector(frustumWidth / 2, frustumHeight / 2);
	}

	@Override
	public void updateFrustum(GL10 gl) {
		Step.log("GUICamera-viewport:"+Step.renderer.getWidth() +" X "+ Step.renderer.getHeight());
		Step.log("GUICamera-frustum:"+ frustumWidth +" X "+ frustumHeight);
		
		gl.glViewport(0, 0, Step.renderer.getWidth(), Step.renderer.getHeight());
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		gl.glOrthof(position.getX() - frustumWidth * zoom / 2,
		position.getX() + frustumWidth * zoom/ 2,
		position.getY() - frustumHeight * zoom / 2,
		position.getY() + frustumHeight * zoom/ 2,
		1, -1);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glLoadIdentity();
		
	}
	
	public void touchToWorld(Vector touch) {
		float x = (touch.getX() / (float) Step.renderer.getWidth()) * frustumWidth * zoom;
		float y = (1 - touch.getY() / (float) Step.renderer.getHeight()) * frustumHeight * zoom;
		touch.set(x, y);
		touch.add(position).sub(frustumWidth * zoom / 2, frustumHeight * zoom / 2);
	}

	public float getZoom() {
		return zoom;
	}

	/**
	 * 放大
	 * @param z
	 */
	public void zoomIn(float zoomDes){		 
		if(zoom <= MIN_ZOOM) zoom = MIN_ZOOM;
		else zoom -= zoomDes;
	}
	
	/**
	 * 缩小
	 * @param zoomInc
	 */
	public void zoomOut(float zoomInc){
		if(zoom >= MAX_ZOOM) zoom = MAX_ZOOM;
		else zoom += zoomInc;
	}
	/**
	 * 设置相机缩放比例
	 * @param zoom 缩放比例
	 */
	public void setZoom(float zoom) {
		this.zoom = zoom < 0 ? 1 : zoom;
	}
}
